package org.example.weboj.handler;

import lombok.Getter;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class RoomManager {
    // 用于存储房间及其对应的 WebSocket 会话
    private static final Map<String, Set<WebSocketSession>> rooms = new HashMap<>();
    @Getter
    private static final Map<String, String> rooms_master = new HashMap<>();

    // 创建房间
    public static void createRoom(String roomName, WebSocketSession session) {
        rooms.putIfAbsent(roomName, new HashSet<>());
        rooms.get(roomName).add(session);
    }

    public static void createRoomMaster(String roomName,String clientId) {
        rooms_master.put(roomName, clientId);
    }

    // 加入房间
    public static boolean joinRoom(String roomName, WebSocketSession session) {
        Set<WebSocketSession> roomSessions = rooms.get(roomName);
        if (roomSessions != null) {
            roomSessions.add(session);
            return true;
        }
        return false;
    }

    // 离开房间
    public static void leaveRoom(String roomName, WebSocketSession session) {
        Set<WebSocketSession> roomSessions = rooms.get(roomName);
        if (roomSessions != null) {
            roomSessions.remove(session);
            if (roomSessions.isEmpty()) {
                rooms.remove(roomName);  // 如果房间没有人了，删除房间
                rooms_master.remove(roomName);
            }
        }
    }

    // 获取房间的 WebSocket 会话
    public static Set<WebSocketSession> getRoomSessions(String roomName) {
        return rooms.get(roomName);
    }

    // 检查房间是否已存在
    public static boolean roomExists(String room) {
        return rooms.containsKey(room);
    }

    public static int getRoomSize(String roomName) {
        Set<WebSocketSession> sessions = rooms.get(roomName);
        return sessions != null ? sessions.size() : 0;
    }
}
